package com.example.day_day_up.servlet;

import com.example.day_day_up.enums.AccountEnum;
import com.example.day_day_up.exception.BusinessException;
import com.example.day_day_up.service.UserService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext servletContext = getServletContext();
        userService = (UserService) servletContext.getAttribute("userService");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int type = Integer.parseInt(req.getParameter("type"));

        if (type == AccountEnum.SIGN_UP.getCode()) {
            userService.sign(req, resp);
        } else if (type == AccountEnum.SIGN_IN.getCode()) {
            userService.login(req, resp);
        } else if (type == AccountEnum.LOGOUT.getCode()) {
            userService.logout(req, resp);
        } else if (type == AccountEnum.RESET_PASSWORD.getCode()) {
            userService.resetPassword(req, resp);
        } else {
            throw new BusinessException("登录方法失败");
        }
    }
}
